package com.tjresearch.redisdbtasktracker.runner;

import java.awt.Color;
import java.awt.Font;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.jfree.chart.ChartFactory;
//import com.tjresearch.genpic.util.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.time.TimeSeriesDataItem;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.XYDataset;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tjresearch.redisdbtasktracker.pojo.ChartData;
import com.tjresearch.redisdbtasktracker.pojo.ItemInfo;
import com.tjresearch.redisdbtasktracker.pojo.PicPath;
import com.tjresearch.redisdbtasktracker.service.DataService;
import com.tjresearch.redisdbtasktracker.service.InsertDbService;

@Component("timeChartsController")
public class TimeChartsController {

	@Autowired
	DataService dataService;
	@Autowired
	private InsertDbService insertDbService;
	@Autowired
	private  PicPath picPath;
	

//	@RequestMapping(value = "/drawTimeCharts")
	// @Scheduled(cron="0 0 6 * * ?")
	public void getHighfreqData() {

//		try {
//			ReaderSqlUtils.insertDb(insertDbService);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		List<ItemInfo> itemList = dataService.getHighfreqItem();
		for (ItemInfo itemInfo : itemList) {
			Integer itemId = itemInfo.getItemId();
			// String itemName = itemInfo.getItemName();
			String indusName = itemInfo.getIndusName();
			String indusRealName = itemInfo.getIndusName();
			String indexName = itemInfo.getIndexName();
			String datatypeName = itemInfo.getDatatypeName();
			String catgName = itemInfo.getCatgName();
			Integer datatypeId = itemInfo.getDatatypeId();
			Integer indexId = itemInfo.getIndexId();
			Integer indusId = itemInfo.getIndusId();
			List<ChartData> data = dataService.getHighfreqData(itemId);

			// 重新规定生成图片的规则itemid-indusid-datatypeid-indexid
			{
				catgName = String.valueOf(itemInfo.getItemId());
				indusName = String.valueOf(itemInfo.getIndusId());
				indexName = String.valueOf(itemInfo.getIndexId());
				datatypeName = String.valueOf(itemInfo.getDatatypeId());
			}

			 createpic(indusRealName,indusName,data,indexName,datatypeName,catgName);
		

		}
	
	}

	public  void createpic(String indusRealName, String indusName, List<ChartData> data, String datatypeName,
			String indexName, String catgName) {
		// 打开一个输出流
		OutputStream outputStream = null;
		// 创建当日文件夹
		String strDate = "";
		Date dt = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		strDate = sdf.format(dt);

		//File file = new File("F:/jfreechart/" + strDate);
		File file = new File(picPath.getJfPath() + strDate);
		if (!file.exists()) {
			file.mkdirs();
		}
		try {
			outputStream = null;
			try {

				outputStream = new FileOutputStream(picPath.getJfPath()+"/" + strDate + "/" + catgName + "-" + indusName + "-"
						+ datatypeName + "-" + indexName + ".png");
//				outputStream = new FileOutputStream("F:/jfreechart/" + strDate + "/" + catgName + "-" + indusName + "-"
//						+ datatypeName + "-" + indexName + ".png");
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}

			// 设置valueAxisLabel名称
			String valueAxisLabelName = "";
			// 不显示valueAxisLabel
			/*
			 * if(datatypeId == 4){ valueAxisLabelName = "同比"; }else
			 * if(datatypeId == 5){ valueAxisLabelName = "环比"; }
			 */

			// 创建主题样式
			StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
			// 设置标题字体
			standardChartTheme.setExtraLargeFont(new Font("宋书", Font.BOLD, 60));
			// 设置图例的字体
			standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 15));
			// 设置轴向的字体
			standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 15));
			// 应用主题样式
			ChartFactory.setChartTheme(standardChartTheme);

		

			XYDataset dataset = createDataset(indusName, data);
			// 创建图形对象
			JFreeChart jfreechart = ChartFactory.createXYBarChart(indusRealName, indusRealName, true,
					valueAxisLabelName, (IntervalXYDataset) dataset);
			// 获得图表区域对象
			XYPlot xyplot = (XYPlot) jfreechart.getPlot();
			// 设置背景颜色
			xyplot.setBackgroundPaint(Color.WHITE);
			xyplot.setOutlinePaint(Color.white);
			// 设置图形颜色
			XYItemRenderer renderer = xyplot.getRenderer();
			renderer.setSeriesPaint(0, new Color(51, 116, 223));

			// 获得X轴对象
			DateAxis domainAxis = (DateAxis) xyplot.getDomainAxis();
			domainAxis.setVisible(false);
			// 获取Y轴对象
			ValueAxis yAxis = xyplot.getRangeAxis();
			yAxis.setVisible(false);
			// 隐藏图例
			jfreechart.removeLegend();
			jfreechart.setBorderVisible(true);
			jfreechart.getXYPlot().setOutlineVisible(false);
			
			// 将图表已数据流的方式返回给客户端
			try {
				ChartUtilities.writeChartAsPNG(outputStream, jfreechart, 500, 170);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		} finally {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 返回数据集
	 * 
	 * @return
	 */
	@SuppressWarnings({})
	private static XYDataset createDataset(String indusName, List<ChartData> data) {
		/*
		 * 尝试使用timeseries
		 */

		// 创建时序对象
		TimeSeries timeseries = new TimeSeries("");

		for (ChartData chartDatas : data) {

			String strDate = chartDatas.getHdate();
			Double value = chartDatas.getValue() * 100;
			Integer yyyy = new Integer(strDate.split("-")[0]);
			Integer mm = new Integer(strDate.split("-")[1]);
			Integer dd = new Integer(strDate.split("-")[2]);
			Day day = new Day(dd, mm, yyyy);

			TimeSeriesDataItem dataItem = new TimeSeriesDataItem(day, value);
			timeseries.add(dataItem);
		}

		TimeSeriesCollection dataset = new TimeSeriesCollection();
		dataset.addSeries(timeseries);
		return dataset;

		
	}

}
